<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>滚动</title>
    <style>
      body {
        background-color: pink;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin: 0;
        overflow-x: hidden;
      }
      h1 {
        margin: 10px;
      }
      .box {
        background-color: skyblue;
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 400px;
        height: 200px;
        margin: 10px;
        border-radius: 10px;
        transform: translateX(400%);
        transition: transform 0.5s ease;
      }
      .box:nth-of-type(even) {
        transform: translateX(-400%);
      }
      .box.show {
        transform: translateX(0);
      }
      .box h2 {
        font-size: 45px;
      }
    </style>
  </head>
  <body>
    <h1>滚动查看效果</h1>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <div class="box">
      <h2>Content</h2>
    </div>
    <script>
      //getBoundingClientRect()
      //获取所有的box
      const boxes = document.querySelectorAll('.box');
      //监听滚动的时候 添加/移除box的 show类名
      window.addEventListener('scroll', checkBoxes);
      //checkBoxes 根据元素距离顶部视窗的高度来控制show类名
      checkBoxes();
      function checkBoxes() {
        //视窗高度
        console.log(window.innerHeight);
        //设置触发的位置 小于视窗 但是效果不太好 我们需要缩小触发高度
        //getBoundingClientRect 返回元素的大小 以及 该元素相对于视口的位置
        boxes.forEach((box) => {
          let triggerHeight = (window.innerHeight * 2) / 3;
          //获取每个box距离顶部视窗的高度
          let boxTop = box.getBoundingClientRect().top;
          //小于视口高度就添加show的类名
          if (boxTop < triggerHeight) {
            box.classList.add('show');
          } else {
            box.classList.remove('show');
          }
        });
      }
    </script>
  </body>
</html>
